/*
使能一定要放前面
*/


#include "BuleTooth.h"

uint8_t tail[4] = {0x00, 0x00, 0x80, 0x7f};/*vofa协议帧尾数据*/

/*联合体将浮点数据转换成4字节数据
*大端数据存储，高字节在低位
*/
union 
{
    unsigned char a[4];
    float b;
}temp;

/*
*@brief:vofa协议发送数据
*@para1:串口号
*@para2:浮点数据
*/
void vofa_send_data(USART_TypeDef* USARTx,float data)
{
    unsigned char i = 0;
    temp .b = data;
    for(i=0;i<4;i++)
    {
        USART_SendData(USARTx,temp .a[i]);
		while (USART_GetFlagStatus(USARTx,USART_FLAG_TXE)==RESET);
    }
}

/*
*@brief:发送vofa协议尾帧
*@para:串口号
*/
void vofa_send_tail(USART_TypeDef* USARTx)
{
    unsigned char i=0;
    for(i=0;i<4;i++)
    {
        USART_SendData(USARTx,tail[i]);
		while (USART_GetFlagStatus(USARTx,USART_FLAG_TXE)==RESET);
    }
}


/*
*@brief:初始化蓝牙
*/
void bluetooth_init(void)
{
    USART_InitTypeDef buletooth_init_struct;
    GPIO_InitTypeDef  GPIO_tx_init_struct;
    GPIO_InitTypeDef  GPIO_rx_init_struct;
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_trx_GPIOx,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_buletooth, ENABLE);
	
    GPIO_tx_init_struct .GPIO_Mode = GPIO_Mode_AF_PP;
    GPIO_tx_init_struct .GPIO_Pin = buletooth_tx_pin;
    GPIO_tx_init_struct .GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_rx_init_struct .GPIO_Mode = GPIO_Mode_IN_FLOATING;
    GPIO_rx_init_struct .GPIO_Pin = buletooth_rx_pin;
    GPIO_Init(buletooth_usart_GPIOx,&GPIO_tx_init_struct);
    GPIO_Init(buletooth_usart_GPIOx,&GPIO_rx_init_struct);
    

    buletooth_init_struct .USART_BaudRate = 115200;
    buletooth_init_struct .USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    buletooth_init_struct .USART_Mode = USART_Mode_Tx | USART_Mode_Rx ;
    buletooth_init_struct .USART_Parity = USART_Parity_No;
    buletooth_init_struct .USART_StopBits = USART_StopBits_1;
    buletooth_init_struct .USART_WordLength = USART_WordLength_8b;
    
    USART_Init(buletooth_usartx , &buletooth_init_struct);   
    USART_Cmd(buletooth_usartx, ENABLE);       
}

/*
*蓝牙接收中断配置
*/
void buletooth_itconfig(void)
{
    USART_ITConfig(buletooth_usartx, USART_IT_RXNE,ENABLE);
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    NVIC_InitTypeDef NVIC_bluetooth_struct;
    NVIC_bluetooth_struct .NVIC_IRQChannel = buletooth_IRQn;
    NVIC_bluetooth_struct .NVIC_IRQChannelCmd = ENABLE;
    NVIC_bluetooth_struct .NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_bluetooth_struct .NVIC_IRQChannelSubPriority = 1;
    NVIC_Init(&NVIC_bluetooth_struct);
}

/*
*蓝牙接收中断服务函数
*/
void USART1_IRQHandler(void)
{
    if(USART_GetITStatus(buletooth_usartx, USART_IT_RXNE)==SET)
    {
        GPIO_ResetBits(GPIOE,GPIO_Pin_5);
    }
    USART_ClearITPendingBit(buletooth_usartx, USART_IT_RXNE);
}
